<?php

namespace app\api\controller;

use app\common\model\QuestionUser;
use app\common\controller\Frontend;

class QuestionCoupon extends Frontend
{
    protected array $noNeedLogin = ['frontPage','lists','details'];


    public function initialize(): void
    {
        parent::initialize();
    }

    public function frontPage()
    {
        $lists = \app\common\model\QuestionCoupon::where(['status' => 1])
            ->order('id desc')
//            ->where('start_time', '<', time())
//            ->where('end_time', '>', time())
            ->limit(2)
            ->select();

        foreach ($lists as &$item) {
            $item->start_time_text = date('Y-m-d', strtotime($item->start_time));
        }

        $this->success('',['lists'=>$lists]);
    }

    public function lists(): void
    {
        $params = $this->request->param();
        $res = \app\common\model\QuestionCoupon::where(['status' => 1])->order('id desc')->paginate($params['limit'] ?? 10);

        foreach ($res->items() as &$item) {
            $item->fill_in = 1;

            if (!empty($this->auth->id)) {
                $questionUser = QuestionUser::where(['user_id' => $this->auth->id,'question_coupon_id' => $item->id])->find();
                if ($questionUser) {
                    $item->fill_in = 2; //已填写
                } else {
                    if ($item->end_time < time()) $item->fill_in = 3;//已过期
                }
            }

            $item->start_time_text = date('Y-m-d', strtotime($item->start_time));
        }

        $this->success('',['lists' => $res->items(),'total' => $res->total()]);
    }

    /**
     */
    public function details(): void
    {

        $params = $this->request->param();
        if (empty($params['id'])) {
            $this->error('问券丢失');
        }
        $row = \app\common\model\QuestionCoupon::find($params['id']);

        $this->success('',['row' => $row]);
    }


    public function answer()
    {
        $params = $this->request->param();
        if (!isset($params['id']) || !isset($params['answer'])) {
            $this->error('请选择回答的问券');
        }
        $result = QuestionUser::create([
            'user_id' => $this->auth->id,
            'question_coupon_id' => $params['id'],
            'answer' => json_encode($params['answer'],JSON_UNESCAPED_UNICODE),
        ]);
        if (!isset($result->id)) $this->error('回答问题错误');
        $this->success('回答成功',$result);
    }

}
